/*
* Copyright (c) 2010 Michael Collins
*
* This file is part of TerraFirma.
*
* TerraFirma is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TerraFirma is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TerraFirma.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "network_pipe.h"
namespace engine
{

    network_pipe::network_pipe(boost::condition_variable& r) : read(r)
    {
        memset(seqs, 0, sizeof(seqs)); //Make all of the sequence numbers 0 in the beginning
        empty = true;
    }

    network_pipe::~network_pipe()
    {
        while(!empty) pop();
    }

    void network_pipe::pop()
    {
        if (!empty)
        {
            boost::lock_guard<boost::mutex> lock(mut);
            queue.pop();
            empty = queue.empty();
        }
    }

    void network_pipe::enqueue(hostid dst, const message_header* msg)
    {
        inter_network_msg cast_msg(*msg);
        cast_msg.header.dest_host = dst;
        //Lock the mutex via a unique lock so that should an exception occur, mutex is unlocked
        //(which is good because this method is basically ASKING for a segfault)
        {
            boost::lock_guard<boost::mutex> lock(mut);
            cast_msg.header.seq = (seqs[dst])++; //Set the sequence number from the one stored in the array, and inc
            queue.push(cast_msg);
            empty = false;
        } //Lock is freed here
        //Signal any threads waiting for the queue to have a message that a message is available
        read.notify_one();
    }


}
